package com.atguigu.exam.service.impl;

import com.atguigu.exam.entity.Banner;
import com.atguigu.exam.mapper.BannerMapper;
import com.atguigu.exam.service.BannerService;
import com.atguigu.exam.service.FileUploadService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.minio.errors.*;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

/**
 * 轮播图服务实现类
 */
@Service
public class BannerServiceImpl extends ServiceImpl<BannerMapper, Banner> implements BannerService {


    @Autowired
    private FileUploadService fileUploadService;


    @Autowired
    private BannerMapper bannerMapper;

    @Override
    public String uploadImage(MultipartFile file) throws ServerException, InsufficientDataException, ErrorResponseException, IOException, NoSuchAlgorithmException, InvalidKeyException, InvalidResponseException, XmlParserException, InternalException {
        if (file.isEmpty()){
            throw new RuntimeException("请选择上传的文件");
        }

        String contentType = file.getContentType();
        if (ObjectUtils.isEmpty(contentType)||!contentType.startsWith("image")){
            throw new RuntimeException("轮播图只能上传照片");
        }

        if (file.getSize()> 5 * 1024 * 1024){
            throw new RuntimeException("文件大小不能超过5MB");
        }

        String img = fileUploadService.upload(file,"banners");

        return img;
    }

    @Override
    public void addBanner(Banner banner) {

         if (banner.getIsActive()==null){
             banner.setIsActive(true);
         }
         if (banner.getSortOrder()==null){
             banner.setSortOrder(0);
         }

        boolean save = save(banner);
         if (!save){
             throw new RuntimeException("图片保存失败");
         }

    }

    @Override
    public void updateBanner(Banner banner) {

        boolean update = this.updateById(banner);
        if (!update){
            throw new RuntimeException("更新轮播图失败");
        }

    }

}